/**
 * Created by zhulizhe on 2017/9/1.
 */
import React, {Component} from 'react';
import {
    View,
    TouchableOpacity,
    DeviceEventEmitter
} from 'react-native';
import Constant from '../Contant'
import {observable, observe} from 'mobx'
import MapView from 'react-native-maps';
import Icon from 'react-native-vector-icons/Ionicons'
import addressMgrStore, {Address} from '../store/AddrMgrStore'


// 地图中间的圆圈
const CenterCircle = () => {
    return <View style={styles.centerCircle}/>
}

// 我的当前位置按钮
const MyLocation = ({onClick}) => {
    return <View style={styles.mapMarker}>
        <TouchableOpacity onPress={onClick}>
            <Icon name="ios-navigate-outline" size={28} color={Constant.TEXTCONTENTCOLOR}/>
        </TouchableOpacity>
    </View>

}

// 地图组件
export default class MapCom extends Component{

    componentDidMount(){
        setTimeout(this.moveToUserLocation.bind(this),500);

        // 地址搜索，点击后更新地图展示位置 事件监听
        this.updateMapListener = DeviceEventEmitter.addListener(Constant.CURRENTLOCATIONCHANGE, (poi)=>{
            let region = addressMgrStore.mapAuto.convertPOI2Region(poi) ;
            this.animateToRegion(region);
        });
    }

    componentWillUnmount(){
        this.updateMapListener.remove();
    };

    // 地图变换了位置回调
    onRegionChange = (r)=>{
        // 更新附近的数据
        addressMgrStore.mapAuto.setMapRegion(r);
    }

    // 转到用户当前位置
    moveToUserLocation = ()=>{
        let currentRegion = addressMgrStore.mapAuto.currentRegion ;
        this.animateToRegion(currentRegion);
    }

    // 地图转到 r 位置
    animateToRegion(r) {
        if (this.mapView != null) {
            this.mapView.animateToRegion(r);
        }
    }

    render(){
        return <View style={{
            flexGrow: 2,
            justifyContent: 'space-between',
            flex: 1
        }}>
            <MapView
                ref={(r) => this.mapView = r}
                onRegionChangeComplete={this.onRegionChange.bind(this)}
                showsUserLocation={true}
                loadingEnabled={true}
                style={styles.map}>
                <CenterCircle/>
            </MapView>
            <MyLocation onClick={this.moveToUserLocation.bind(this)}/>
        </View>
    }
}

const styles = {
    map: {
        flex: 1,
        backgroundColor: Constant.GRAYBGCOLOR,
        justifyContent: 'center',
        alignItems: 'center'
    },
    centerCircle: {
        backgroundColor: 'rgba(255,215,0,1)',
        justifyContent: 'center',
        alignItems: 'center',
        width: 24,
        height: 24,
        borderRadius: 12,
        borderWidth: 2,
        borderColor: Constant.BLUECOLOR
    },
    mapMarker: {
        position: 'absolute',
        width: 30,
        height: 30,
        borderRadius: 15,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#00000000',
        bottom: 15,
        left: 15

    }
}
